const User = require("../../models/blog_user");
const Validate = require("../../utils/validate");
const authCodeFunc = require("../../utils/authCode");

const ControllerUser = {
    /* 登录 */
    userLogin: async function (req, res, next) {
        try {
            let { account, password } = req.body;
            let params = {};

            if (Validate.isEmail(account)) {
                params.email = account;
            } else {
                params.account = account;
            }

            const users = await User.select(params);
            let user = users[0];

            if (user) {
                if (user.password != password)
                    return res.json({ code: 0, msg: "密码错误" });

                let auth_Code = user.id + "\t" + user.account + "\t" + user.password;
                let userInfo = {
                    name: user.name ? user.name : user.account,
                    avatar: user.avatar_url,
                };

                const token = authCodeFunc(auth_Code, "ENCODE");

                res.json({ code: 200, msg: "登陆成功", data: { token, userInfo } });
            } else {
                res.json({ code: 0, msg: "用户不存在" });
            }
        } catch (e) {
            res.json({ code: 0, data: e });
        }
    },

    /* 注册 */
    userRegister: async function (req, res, next) {
        try {
            let { account, email, password, okpassword } = req.body;
            // let avatar_url = 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png';

            const accounts = await User.select({ account });
            const emails = await User.select({ email });

            if (accounts.length > 0)
                return res.json({ code: 0, msg: "该用户已被注册" });

            if (emails.length > 0)
                return res.json({ code: 0, msg: "该邮件已被注册" });

            if (!account || !email || !password || !okpassword)
                return res.json({ code: 0, msg: "缺少必要参数" });

            if (password != okpassword)
                return res.json({ code: 0, msg: "确认密码不一致" });

            if (!Validate.isEmail(email))
                return res.json({ code: 0, msg: "电子邮件格式错误" });

            await User.insert({
                account,
                email,
                password,
                created_at: new Date().getTime(),
            });

            res.json({ code: 200, msg: "注册成功" });
        } catch (e) {
            res.json({ code: 0, data: e });
        }
    },

    /* 用户详情 */
    getById: async function (req, res, next) {
        try {
            let authorization = req.headers.authorization;
            let user_id;

            if (authorization) {
                let token = authorization.split(" ");
                let user_decode = authCodeFunc(token[1], "DECODE");
                let user_info = user_decode.str.split("\t");
                user_id = user_info[0];
            }

            const users = await User.select({ id: user_id });
            res.json({ code: 200, msg: "链接成功", data: users[0] });
        } catch (e) {
            res.json({ code: 0, data: e });
        }
    },

    /* 修改用户信息 */
    update: async function (req, res, next) {
        try {
            let { account, name, email, avatar_url } = req.body;
            let authorization = req.headers.authorization;
            let id;

            let params = {
                account,
                name,
                email,
                avatar_url,
                updated_at: new Date().getTime(),
            };

            let userInfo = {
                name: name ? name : account,
                avatar: avatar_url,
            };

            if (authorization) {
                let token = authorization.split(" ");
                let user_decode = authCodeFunc(token[1], "DECODE");
                let user_info = user_decode.str.split("\t");
                id = user_info[0];
            }

            await User.update(id, params);

            res.json({ code: 200, msg: "保存成功", data: { userInfo } });
        } catch (e) {
            res.json({ code: 0, data: e });
        }
    },

    /* 用户个人密码修改 */
    updatePassword: async function (req, res, next) {
        try {
            let { password, newpassword, okpassword } = req.body;
            let authorization = req.headers.authorization;
            let user_info;

            if (authorization) {
                let token = authorization.split(" ");
                let user_decode = authCodeFunc(token[1], "DECODE");
                user_info = user_decode.str.split("\t");
            }

            if (user_info[2] != password)
                return res.json({ code: 0, msg: "原密码错误" });

            if (newpassword != okpassword)
                return res.json({ code: 0, msg: "确认密码错误" });

            let id = user_info[0];
            let auth_Code = id + "\t" + user_info[1] + "\t" + newpassword;
            const token = authCodeFunc(auth_Code, "ENCODE");

            await User.update(id, { password: newpassword });

            res.json({ code: 200, msg: "修改成功", data: { token } });
        } catch (e) {
            res.json({ code: 0, data: e });
        }
    },
};

module.exports = ControllerUser;
